<?php
/**
 * 专门测试图片上传的脚本
 */

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/oss_config.php';

use AlibabaCloud\Oss\V2 as Oss;

// 模拟getOssConfig函数
function getOssConfig() {
    $configFile = __DIR__ . '/oss_config.php';
    if (file_exists($configFile)) {
        $config = include $configFile;
        if (isset($config['access_key_id']) && isset($config['access_key_secret'])) {
            return $config;
        }
    }
    return null;
}

// 模拟httpGet函数（修复版本）
function httpGet($url) {
    $curl = curl_init();

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_URL, $url);

    // 重要：设置二进制传输模式
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

    // 设置用户代理
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');

    // 禁用SSL验证（Windows环境）
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $res = curl_exec($curl);

    if (curl_error($curl)) {
        $error = curl_error($curl);
        curl_close($curl);
        throw new Exception("HTTP请求失败: " . $error);
    }

    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    if ($httpCode !== 200) {
        curl_close($curl);
        throw new Exception("HTTP请求返回错误状态码: " . $httpCode);
    }

    curl_close($curl);
    return $res;
}

try {
    echo "=== 图片上传测试 ===\n";

    $ossConfig = getOssConfig();
    if (!$ossConfig) {
        die("无法获取OSS配置\n");
    }

    echo "配置信息:\n";
    echo "Access Key ID: " . substr($ossConfig['access_key_id'], 0, 8) . "...\n";
    echo "Region: " . $ossConfig['region'] . "\n";
    echo "Bucket: " . $ossConfig['bucket_name'] . "\n\n";

    // 创建凭证提供者
    $credentialsProvider = new Oss\Credentials\StaticCredentialsProvider(
        $ossConfig['access_key_id'],
        $ossConfig['access_key_secret']
    );

    // 创建配置
    $cfg = new Oss\Config();
    $cfg->setCredentialsProvider($credentialsProvider);
    $cfg->setRegion($ossConfig['region']);
    $cfg->setEndpoint($ossConfig['endpoint']);
    $cfg->setConnectTimeout(30);

    // 创建客户端
    $client = new Oss\Client($cfg);

    // 测试不同的图片数据源
    $testUrls = [
        'https://opencdn.ydsjt.cn/image/20251018/1760782635720_476071.jpg',
        'https://via.placeholder.com/100x100.jpg',
        'https://picsum.photos/200/200.jpg'
    ];

    foreach ($testUrls as $index => $testUrl) {
        echo "\n--- 测试 " . ($index + 1) . " ---\n";
        echo "测试URL: " . $testUrl . "\n";

        try {
            // 获取图片数据
            $imageData = httpGet($testUrl);

            if (empty($imageData)) {
                echo "❌ 无法获取图片数据\n";
                continue;
            }

            echo "图片数据大小: " . strlen($imageData) . " bytes\n";
            echo "数据类型: " . gettype($imageData) . "\n";
            echo "是否二进制: " . (ctype_print($imageData) ? '否' : '是') . "\n";
            echo "前10字节: " . bin2hex(substr($imageData, 0, 10)) . "\n";

            // 生成文件名
            $filename = "/uploads/wx/test_" . time() . "_" . $index . ".jpg";

            // 创建上传请求（使用构造函数参数）
            $request = new Oss\Models\PutObjectRequest($ossConfig['bucket_name'],$filename);

            echo "正在上传...\n";

            // 执行上传
            $result = $client->putObject($request);

            echo "上传结果:\n";
            echo "状态码: " . $result->statusCode . "\n";

            if ($result->statusCode == 200) {
                $url = "http://{$ossConfig['bucket_name']}.oss-{$ossConfig['region']}.aliyuncs.com/".$filename;
                echo "✅ 上传成功！\n";
                echo "文件URL: " . $url . "\n";
                break; // 成功一个就够了
            } else {
                echo "❌ 上传失败\n";
            }

        } catch (Exception $e) {
            echo "❌ 测试失败: " . $e->getMessage() . "\n";
        }
    }

} catch (Exception $e) {
    echo "❌ 测试脚本失败！\n";
    echo "错误信息: " . $e->getMessage() . "\n";
    echo "错误代码: " . $e->getCode() . "\n";
    echo "错误类型: " . get_class($e) . "\n";
}
?>
